<?php
/**
 * 名称：AppsAction
 * 描述：应用管理
 * 作者：sun 时间：2013-05-02
 * 版本号：V1.0.0
 * ========================历史版本=================================
 * 序号	 版本号 	日期			姓名	 	描述
 * 1 	V1.0.0 	2013-05-02 	sun  	应用管理
 * ========================历史版本=================================
 * 说明：请在有更改程序的时候修改以上注释
 */
class AppsAction extends CommonAction {
	 /**
	 * 已安装应用列表
	 * Create Data <2013-05-02>
	 */
	public function appsList() {
		$installed = model('App')->order('display_order ASC')->findPage(20);
		$this->assign($installed);
		$this->display();
	}
	
	/**
	 * 待安装应用列表
	 * Create Data <2013-05-02>
	 */
	public function appsInstall() {
		$uninstalled = array();
		$installed 	 = model('App')->getAllApp('app_name');
		$installed   = common('Array')->getSubByKey($installed, 'app_name');
		//默认应用,不能安装卸载.
		$installed = array_merge($installed, C('DEFAULT_APPS'));
		
		import("ORG.Io.Dir");
		$dirs	= new Dir(SITE_PATH.'/apps/');
		$dirs	= $dirs->toArray();
		foreach($dirs as $v){
			if ( $v['isDir'] && !in_array($v['filename'], $installed) ) {
				if ( $info = $this->_getAppInfo($v['filename']) ) {
					$uninstalled[]	= $info;
				}
			}
		}
		$this->assign('uninstalled', $uninstalled);
		$this->display();
	}
	
	/**
	 * 应用安装页面
	 * Create Data <2013-05-02>
	 */
	public function preinstall() {
		$info = $this->_getAppInfo($_GET['path_name']);
		$this->assign($info);
		$this->display('edit');
	}
	
	/**
	 * 应用安装
	 * Create Data <2013-05-02>
	 */
	public function doInstall() {
		$_POST['path_name'] = common('Html')->text($_POST['path_name']);
		$info = $this->_getAppInfo($_POST['path_name']);
		if (!$info)
			$this->error(L('parameterError'));
	
		if (model('App')->isAppNameInstall($_POST['path_name']))
			$this->error(L('existsApp'));
		$install_script = SITE_PATH . "/apps/{$info['path_name']}/Appinfo/install.php";
		if (is_file($install_script))
			include_once $install_script;
		if (!$this->_updateApp('add', $info))
			$this->error(L('installFailed'));
	
		model('App')->unsetSiteDefaultApp();
		model('App')->unsetUserInstalledApp($this->mid);
	
		// 设置版本号
		model('Data')->put("{$info['app_name']}:version_number", $info['version_number'], true);
		$this->assign('jumpUrl', URL('admin/Apps/appsInstall'));
		$this->success(L('installSucceed'));
	}

	/**
	 * 进入编辑应用页
	 * Create Data <2013-05-02>
	 */
	public function edit() {
		$info = model('App')->getAppDetailById(intval($_GET['app_id']));
		$info['path_name']			= $info['app_name'];
		$info['host_type_alias']	= $info['host_type'] == 0 ?L('localApp'):L('remoteApp'); //$host_type[$info['host_type']];
		$this->assign($info);
		$this->display();
	}
	
	/**
	 * 应用安装页面
	 * Create Data <2013-05-02>
	 */
	public function doEdit() {
		if (! is_file(SITE_PATH . '/apps/' . $_POST['app_name'] . '/Appinfo/info.php') ) {
			$this->error(L('editFailed'));
		}
		if ( model('App')->isAppNameInstall($_POST['app_name'], intval($_POST['app_id'])) ) {
			$this->error(L('editExistsFailed'));
		}
		if ( ! $this->_updateApp('save') ) {
			$this->error(L('saveFails'));
		}else {
			model('App')->unsetSiteDefaultApp();
			model('App')->unsetUserInstalledApp($this->mid);
				
			$this->assign('jumpUrl', URL('admin/Apps/appsList'));
			$this->success(L('saveSuccess'));
		}
	}
	
	/**
	 * 卸载应用
	 * Create Data <2013-05-02>
	 */
	public function uninstall() {
		$_POST['app_id'] = intval($_GET['app_id']);
		$app_name = model('App')->where('`app_id`='.$_POST['app_id'])->getField('app_name');
	
		if ( ! $app_name ) {
			$this->error(L('notExistApp'));
		}
	
		$uninstall_script = SITE_PATH . "/apps/{$app_name}/Appinfo/uninstall.php";
		if ( is_file($uninstall_script) ) {
			include_once $uninstall_script;
		}
	
		$_LOG['uid'] = $this->mid;
		$_LOG['type'] = '2';
		$data[] = L('apps').' - '.L('uninstallApp');
		$data[] =  $this->_getAppInfo($app_name);
		$_LOG['data'] = serialize($data);
		$_LOG['ctime'] = time();
		M('AdminLog')->add($_LOG);
	
		if ( ! model('App')->deleteApp($_POST['app_id']) ) {
			$this->error(L('uninstallFailed'));
		}
	
		model('App')->unsetSiteDefaultApp();
		model('App')->unsetUserInstalledApp($this->mid);
	
		$this->assign('jumpUrl', URL('admin/Apps/appsList'));
		$this->success(L('uninstallSucceed'));
	}
	
	/**
	 * 应用状态设置
	 * Create Data <2013-05-02>
	 */
	public function setStatus() {
		$post['app_id'] = intval($_POST['app_id']);
		$post['status'] = intval($_POST['status']);
	
		$_LOG['uid']  = $this->mid;
		$_LOG['type'] = '3';
		$data[] = L('apps').' - '.L('setState');
		$data[] = $_POST;
		$_LOG['data'] = serialize($data);
		$_LOG['ctime'] = time();
		M('AdminLog')->add($_LOG);
		if (M('app')->save($post)) {
			model('App')->unsetSiteDefaultApp();
			model('App')->unsetUserInstalledApp($this->mid);
			model('App')->resetAppCache($_POST['app_id']);
			echo '1';
		}else {
			echo '0';
		}
	}
	
	/**
	 * 应用位置排序
	 * Create Data <2013-05-02>
	 */
	public function setAppOrder() {
		$_POST['app_id'] = intval($_POST['app_id']);
		$_POST['baseid'] = intval($_POST['baseid']);
		if ( $_POST['app_id'] <= 0 || $_POST['baseid'] <= 0 ) {
			echo 0;
			exit;
		}
	
		$_LOG['uid'] = $this->mid;
		$_LOG['type'] = '3';
		$data[] = L('apps').' - '.L('setSort');
		$data[] = $_POST;
		$_LOG['data'] = serialize($data);
		$_LOG['ctime'] = time();
		M('AdminLog')->add($_LOG);
	
		$dao = model('App');
		$res = $dao->getAppDetailById( array($_POST['app_id'], $_POST['baseid']), 'app_id,display_order,app_name' );
	
		if ( count($res) < 2 ) {
			echo 0;
			exit;
		}
	
		//转为结果集为array('id'=>'order')的格式
		foreach($res as $v) {
			$order[$v['app_id']] = intval($v['display_order']);
		}
		unset($res);
	
		//交换order值
		$res = 		   $dao->where('`app_id`=' . $_POST['app_id'])->setField( 'display_order', $order[$_POST['baseid']] );
		if($res){
			$res = $dao->where('`app_id`=' . $_POST['baseid'])->setField( 'display_order', $order[$_POST['app_id']] );
		}
	
		model('App')->unsetSiteDefaultApp();
		model('App')->unsetUserInstalledApp($this->mid);
	
		echo $res?1:0;
	}
	
	/**
	 * 获取应用信息
	 * Create Data <2013-05-02>
	 */
	private function _getAppInfo($path_name, $using_lowercase = true) {
		$filename = SITE_PATH . '/apps/' . $path_name . '/Appinfo/info.php';
		if ( is_file($filename) ) {
			$info = include_once $filename;
			$info['HOST_TYPE_ALIAS']	= $info['host_type'] == 0 ?L('localApp'):L('remoteApp');
			$info['APP_ALIAS']			= $info['NAME'];
			$info['PATH_NAME'] 			= $path_name;
			$info['APP_NAME']			= $path_name;
			$info['CONTRIBUTOR_NAME']	= $info['CONTRIBUTOR_NAMES'];
			return $using_lowercase ? array_change_key_case($info) : array_change_key_case($info,CASE_UPPER);
		}else {
			return null;
		}
	}
	
	/**
	 * 安装/编辑 应用
	 * Create Data <2013-05-02>
	 */
	private function _updateApp($method, $info) {
		if ( !in_array($method, array('add','save')) ) {
			return false;
		}
		$_LOG['uid'] = $this->mid;
	
		if ($method == 'add') {
			$data['host_type']					= intval($info['host_type']);
			$data['homepage_url']				= $info['homepage_url'];
			$data['sidebar_support_submenu']	= intval($info['sidebar_support_submenu']);
			$data['author_name']				= $info['author_name'];
			$data['author_email']				= $info['author_email'];
			$data['author_homepage_url']		= $info['author_homepage_url'];
			$data['contributor_name']			= $info['contributor_names'];
			$data['release_date']				= $info['release_date'];
			$data['last_update_date']			= $info['last_update_date'];
			$data['isalone']					= $info['isalone'];
			$data['version']					= $info['version_number'];
			$data['ishomeshow']					= isset($info['ishomeshow'])?$info['ishomeshow']:1;
			$_LOG['type'] = '1';
			$log_data[] = L('apps').' - '.L('installApp');
	
		}else {
	
			$_LOG['type'] = '3';
			$log_data[] = L('apps').' - '.L('editApp');
	
			$data['app_id']						= intval($_POST['app_id']);
		}
	
		$data['app_name']					= $method=='add' ? common('Html')->text($_POST['path_name']) : common('Html')->text($_POST['app_name']);
		$data['app_alias']					= common('Html')->text($_POST['app_alias']);
		$data['description']				= htmlspecialchars($_POST['description']);
		$data['status']						= intval($_POST['status']);
		$data['category']					= common('Html')->text($_POST['category']);
		$data['app_entry']					= common('Html')->text($_POST['app_entry']);
		$data['icon_url']					= common('Html')->text($_POST['icon_url']);
		$data['large_icon_url']				= common('Html')->text($_POST['large_icon_url']);
		$data['admin_entry']				= common('Html')->text($_POST['admin_entry']);
		$data['statistics_entry']			= common('Html')->text($_POST['statistics_entry']);
		$data['sidebar_title']				= common('Html')->text($_POST['sidebar_title']);
		$data['sidebar_entry']				= common('Html')->text($_POST['sidebar_entry']);
		$data['sidebar_icon_url']			= common('Html')->text($_POST['sidebar_icon_url']);
		$data['sidebar_is_submenu_active']	= intval($_POST['sidebar_is_submenu_active']);
		$data['ctime']						= time();
	
		if( $method != 'add' ){
			$appinfo = $this->_getAppInfo($data['app_name']);
			$str = 'name,host_type,homepage_url,release_date,last_update_date,sidebar_support_submenu,author_name,author_email,author_homepage_url,contributor_names,host_type_alias,path_name';
			$arr = explode(',', $str);
			foreach($arr as $v){
				unset($appinfo[$v]);
			}
			$log_data[] = $appinfo;
		}
		$editlater = $data;
		unset($editlater[status]);
		unset($editlater[ctime]);
		$log_data[] = $editlater;
		$_LOG['data'] = serialize($log_data);
		$_LOG['ctime'] = time();
		M('AdminLog')->add($_LOG);
	
		$res = model('App')->$method($data);
		if ($res && $method = 'add') {
			//为排序方便，将order = id
			model('App')->where('`app_id`='.$res)->setField('display_order', $res);
		}
		return $res;
	}
}
?>